package com.etalk.crm.serviceImpl;
import java.time.chrono.ChronoLocalDate;
import	java.time.format.DateTimeFormatter;
import	java.util.HashMap;
import	java.util.ArrayList;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.client.InvokingService;
import com.etalk.crm.dao.*;
import com.etalk.crm.pojo.*;
import com.etalk.crm.service.KcOrdersService;
import com.etalk.crm.service.PersonService;
import com.etalk.crm.service.StuDynamicService;
import com.etalk.crm.service.UserService;
import com.etalk.crm.utils.DateUtil;
import com.etalk.crm.utils.EncryptAndDecrypt;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * @author: James
 * @date: 2019/1/18 10:37
 * @Description:
 */
@Service
public class PersonServiceImpl implements PersonService {
    private static final Logger logger = LogManager.getLogger(PersonServiceImpl.class);
    @Resource
    private PersonMapper personMapper;
    @Resource
    private StoresMapper storesMapper;
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Resource
    CcgetstudentMapper ccgetstudentMapper;
    @Resource
    private GrabOrderLogsMapper grabOrderLogsMapper;
    @Resource
    private StuAutoBookClassTimeMapper stuAutoBookClassTimeMapper;
    @Resource
    private StudentJoinDispositionMapper studentJoinDispositionMapper;
    @Resource
    private LessonsMapper lessonsMapper;
    @Resource
    private UserService userService;
    @Resource
    private KcOrdersService kcOrdersService;
    @Resource
    private StuDynamicService stuDynamicService;
    @Resource
    private InvokingService invokingService;
    @Resource
    private HttpSession session;

    @Override
    public List<Map<String, Object>> selectExperienceInfo(Integer state) {
        return personMapper.selectExperienceInfo(state);
    }

    @Override
    public List<Stores> storesList() {
        return storesMapper.storesList();
    }

    @Override
    public List<Agents> agentsList() {
        return personMapper.agentsList();
    }

    @Override
    public List<Map<String, Object>> channeList() {
        return personMapper.channeList();
    }

    @Override
    public List<Map<String, Object>> selectRevisitInfo(Integer state) {
        return personMapper.selectRevisitInfo(state);
    }

    @Override
    public List<Map<String,Object>> searchLtTeacher(){
        return personMapper.selectLtTeacher();
    }

    @Override
    public List<Map<String,Object>> searchLctTeacher(){
        return personMapper.selectLctTeacher();
    }

    @Override
    public StudentInfo searchStudentInfoById(int personId) {
        return studentInfoMapper.searchStudentInfoById(personId);
    }

    @Override
    public StudentInfo selectStudentInfoByPersonId(int personId) {
        return personMapper.selectStudentInfoByPersonId(personId);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateByPersonId(StudentInfo studentInfo) {
        return personMapper.updateByPersonId(studentInfo);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateStuInfo(StudentInfo studentInfo) {
        int flag = personMapper.phoneNumIsExist(studentInfo.getPhone(),studentInfo.getPersonId(),studentInfo.getLoginName());
        if(flag >0){
            //手机号已存在
            return -1;
        }
        if(studentInfo.getClassTime() != null && !"".equals(studentInfo.getClassTime())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            try {
                studentInfo.setReleaseTime(sdf.parse(studentInfo.getClassTime()));
            } catch (ParseException e) {
                logger.error(e.getMessage(),e);
            }
        }else{
             studentInfo.setReleaseTime(null);
        }
        Integer sscId=personMapper.selectSscIdByPersonId(studentInfo.getPersonId());
        int result = personMapper.updateByPersonId(studentInfo);
        if(result > 0){
            personMapper.updateStuInfo(studentInfo);

            //添加用户性格属性
            this.addPersonDisposition(studentInfo.getPersonId(),studentInfo.getDispositionId());

            //判断ssc是否有改变
            boolean isChangeSsc=studentInfo.getSscId()!=null && studentInfo.getSscId()>0 && (sscId==null || sscId==0 || !sscId.equals(studentInfo.getSscId()));
            if (isChangeSsc){
                //添加好友
                Integer sscPersonId=personMapper.selectPersonIdByUserId(studentInfo.getSscId());
                if (sscPersonId!=null && sscPersonId>0) {
                    invokingService.addFriend(studentInfo.getPersonId(), sscPersonId);
                }
                List<GrabOrderLogs> logList = new ArrayList<>();
                GrabOrderLogs gl = new GrabOrderLogs();
                User users = userService.selectByPrimaryKey(studentInfo.getSscId());
                gl.setPersonId(studentInfo.getPersonId());
                gl.setOperationEvent("成功配置SSC：" + users.getLoginName());
                gl.setDescription("学生管理->学生基本信息(修改)->配置SSC");
                gl.setOldCcSsc(sscId==null?0:sscId);
                gl.setTypeId(6);
                gl.setNewCcSsc(studentInfo.getSscId());
                this.addGrabOrderLogs(gl);
            }
        }
        return result;
    }

    /**
     * 动态中修改到店状态
     * @param personId 学员id
     * @param classStores 到店状态：1是 0否
     * @return 记录数
     */
    @Override
    public int updateClassStoresByPersonId(int personId,int classStores){
        return personMapper.updateClassStoresByPersonId(personId,classStores);
    }
    @Override
    public List<StuPreferences> selectOftenClassTimeConf() {
        return personMapper.selectOftenClassTimeConf(null);
    }

    @Override
    public List<Map<String, Object>> selectSceneInfo(Integer personId) {
        return personMapper.selectSceneInfo(personId);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addSceneInfo(JSONObject jsonObject, String addUserName) {
        Integer personId = jsonObject.getInteger("personId");
        //转换成  list
        List<Map> objectList = (List<Map>) jsonObject.get("prefVal");
        PersonJoinSceneInfo pjsi;
        List<PersonJoinSceneInfo> prefVal = new ArrayList<>();
        for (Map map : objectList) {
            pjsi = new PersonJoinSceneInfo();
            pjsi.setSceneInfoId(Integer.parseInt(map.get("sceneInfoId").toString()));
            if (map.containsKey("customValue")) {
                pjsi.setCustomValue(map.get("customValue").toString());
            }
            pjsi.setPersonId(personId);
            pjsi.setCreater(addUserName);
            prefVal.add(pjsi);
        }
        //判断中教学习建议是否需要保存
        if (jsonObject.containsKey("ltSuggestion")) {
            int countNum = personMapper.countStudentSuggestionByPersonId(personId);
            if (countNum == 0) {
                personMapper.insertStudentSuggestion(personId, jsonObject.getString("ltSuggestion"), addUserName);
            } else {
                personMapper.updateStudentSuggestionByPersonId(personId, jsonObject.getString("ltSuggestion"));
            }
        }
        Map<String,Object> parameMap = new HashMap<>(2);
        parameMap.put("personId", personId);
        parameMap.put("list", prefVal);
        //删除原有的偏好设置
        personMapper.deletePersonSceneInfoByPersonId(parameMap);
        return personMapper.insertSceneInfo(prefVal);
    }

    @Override
    public PageInfo<LessonAndTeacher> selectFiveStartTeacher(int personId,int page, int size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(personMapper.selectFiveStartTeacher(personId));
    }

    @Override
    public List<LessonAndTeacher> selectBlackList(int personId) {
        return personMapper.selectBlackList(personId);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int delBadTeacher(int id) {
        return personMapper.delBadTeacher(id);
    }

    @Override
    public List<LessonAndTeacher> searchByTeacherName(String teacherLogin) {
        return personMapper.searchByTeacherName(teacherLogin);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addBadTeacher(String teacherLogin, int personId) {
        if(personMapper.searchBadTeacherByName(teacherLogin,personId) > 0){
            return -1;
        }else{
            return personMapper.addBadTeacher(teacherLogin,personId);
        }
    }

    @Override
    public PageInfo<LessonAndTeacher> sysTeacherInfo(Integer page, Integer size,StuPreferences stuPreferences) throws ParseException {

        //查询套餐绑定的老师组id
        List<Integer> effectiveOrders = personMapper.effectiveOrders(stuPreferences.getPersonId());

        if(effectiveOrders != null && effectiveOrders.size()>0){
            stuPreferences.setEffectiveOrders(effectiveOrders);
        }else {
            return new PageInfo<>(new ArrayList<>(0));
        }
        //计算未来两周内的约课日期时间
        List<StuAutoBookClassTime> listInfo=stuAutoBookClassTimeMapper.selectAutoBookClassTimeInfoByPersonId(stuPreferences.getPersonId());
        //获取上周日日期
        LocalDate localDate=LocalDate.now().with(TemporalAdjusters.previous(java.time.DayOfWeek.SUNDAY));
        List<String> listDate=new ArrayList<>(14);
        List<String> listNextDate= new ArrayList<> (7);
        for (StuAutoBookClassTime result:listInfo){
            String tempDate=localDate.plusDays(result.getWeekId()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" "+result.getClassTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            //获取本周剩余可约课时间
            if (DateUtils.addHours(DateUtils.parseDate(tempDate,"yyyy-MM-dd HH:mm:ss"),-1).getTime()>DateUtil.getDayStamp()){
                listDate.add(tempDate);
            }
            //获取下周时间
            String nextWeekDate=localDate.plusDays(result.getWeekId()+7).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" "+result.getClassTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            listDate.add(nextWeekDate);
            listNextDate.add(nextWeekDate);
        }
        stuPreferences.setListReleaseDate(listDate);
        stuPreferences.setListNextDate(listNextDate);
        //本周日日期
        stuPreferences.setWeekSunday(localDate.plusDays(7).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        //查询相同时间已被设置常用老师的id
        List<Integer> listTeaId=stuAutoBookClassTimeMapper.selectTeacherIdByPersonId(listNextDate,stuPreferences.getWeekSunday());
        stuPreferences.setListTeaId(listTeaId);

        PageHelper.startPage(page, size);
        PageInfo<LessonAndTeacher> pageInfo=new PageInfo<>(personMapper.sysTeacherInfo(stuPreferences));
        if (pageInfo.getList()!=null && pageInfo.getList().size()>0){
            int autoCount=stuAutoBookClassTimeMapper.selectCountByPersonId(stuPreferences.getPersonId());
            for (LessonAndTeacher record:pageInfo.getList()){
                record.setCountMatchNum(autoCount);
                if (autoCount==0){
                    record.setMatchPercent(BigDecimal.ZERO);
                }else {
                    record.setMatchPercent(BigDecimal.valueOf(record.getMatchNum()).divide(BigDecimal.valueOf(autoCount),4,BigDecimal.ROUND_HALF_UP));
                }
            }
        }
        return pageInfo;
    }

    @Override
    public List<LessonAndTeacher> commonlyUsedTeacherInfo(int personId) throws ParseException {
        LessonAndTeacher teacherInfoById = personMapper.teacherIdsInfoByPersonId(personId);
        List<Integer> list = new ArrayList<>();
        list.add(teacherInfoById.getTeacher1());
        list.add(teacherInfoById.getTeacher2());
        list.add(teacherInfoById.getTeacher3());

        //计算未来两周内的约课日期时间
        List<StuAutoBookClassTime> listInfo=stuAutoBookClassTimeMapper.selectAutoBookClassTimeInfoByPersonId(personId);
        //获取上周日日期
        LocalDate localDate=LocalDate.now().with(TemporalAdjusters.previous(java.time.DayOfWeek.SUNDAY));
        List<String> listDate=new ArrayList<>(14);
        List<String> listNextDate= new ArrayList<> (7);
        for (StuAutoBookClassTime result:listInfo){
            String tempDate=localDate.plusDays(result.getWeekId()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" "+result.getClassTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            //获取本周剩余可约课时间
            if (DateUtils.addHours(DateUtils.parseDate(tempDate,"yyyy-MM-dd HH:mm:ss"),-1).getTime()>DateUtil.getDayStamp()){
                listDate.add(tempDate);
            }
            //获取下周时间
            String nextWeekDate=localDate.plusDays(result.getWeekId()+7).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" "+result.getClassTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            listDate.add(nextWeekDate);
            listNextDate.add(nextWeekDate);
        }
        //如果没有设置自动约课时间，则取一个当前时间
        if (listDate.size()==0){
            listDate.add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            listNextDate.add(listDate.get(0));
        }
        List<LessonAndTeacher> teacherList = personMapper.selectTeacherLevelInfo(personId,list,listDate,listNextDate,localDate.plusDays(7).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        List<LessonAndTeacher> teacherList2 = new ArrayList<>();
        LessonAndTeacher lt1 = null;
        LessonAndTeacher lt2 = null;
        LessonAndTeacher lt3 = null;
        int autoCount=stuAutoBookClassTimeMapper.selectCountByPersonId(personId);
        for(LessonAndTeacher lt : teacherList){
            lt.setCountMatchNum(autoCount);
            if(lt.getPersonId() == teacherInfoById.getTeacher1()){
                lt1 = lt;
            }
            if(lt.getPersonId() == teacherInfoById.getTeacher2()){
                lt2 = lt;
            }
            if(lt.getPersonId() == teacherInfoById.getTeacher3()){
               lt3 = lt;
            }
        }
        if(lt1 != null){
            teacherList2.add(lt1);
        }else if (teacherInfoById.getTeacher1()>0){
            lt1 =new LessonAndTeacher();
            lt1.setPersonId(teacherInfoById.getTeacher1());
            lt1.setTeacherLogin("老师不存在");
            lt1.setAppointmentPercent(BigDecimal.ZERO);
            lt1.setFiveStarPercent(BigDecimal.ZERO);
            teacherList2.add(lt1);
        }
        if(lt2 != null){
            teacherList2.add(lt2);
        }else if (teacherInfoById.getTeacher2()>0){
            lt2 =new LessonAndTeacher();
            lt2.setPersonId(teacherInfoById.getTeacher2());
            lt2.setTeacherLogin("老师不存在");
            lt2.setAppointmentPercent(BigDecimal.ZERO);
            lt2.setFiveStarPercent(BigDecimal.ZERO);
            teacherList2.add(lt2);
        }
        if(lt3 != null){
            teacherList2.add(lt3);
        }else if (teacherInfoById.getTeacher3()>0){
            lt3 =new LessonAndTeacher();
            lt3.setPersonId(teacherInfoById.getTeacher3());
            lt3.setTeacherLogin("老师不存在");
            lt3.setAppointmentPercent(BigDecimal.ZERO);
            lt3.setFiveStarPercent(BigDecimal.ZERO);
            teacherList2.add(lt3);
        }
        return teacherList2;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addCommonlyUsedTeacher(int personId, int teacherId) throws ParseException {
        //常用老师已存在
        if(personMapper.teacherIsExist(personId,teacherId) > 0){
            return -1;
        }
        LessonAndTeacher lessonAndTeacher = personMapper.teacherIdsInfoByPersonId(personId);
        LessonAndTeacher lessonAndTeacher2 = new LessonAndTeacher();
        int count = 0;
        int type = 0;
        if(lessonAndTeacher.getTeacher1() == 0){
            lessonAndTeacher2.setTeacher1(teacherId);
            type = 1;
        }else{
             count++;
        }
        if(lessonAndTeacher.getTeacher2() == 0 && type !=1){
             lessonAndTeacher2.setTeacher2(teacherId);
             type = 2;
        }else{
            count++;
        }

        if(lessonAndTeacher.getTeacher3() == 0 && type != 1 && type != 2){
            lessonAndTeacher2.setTeacher3(teacherId);
        }else{
             count++;
        }
        if(count == 3){
            return -2;
        }
        lessonAndTeacher2.setPersonId(personId);
        int num = personMapper.addTeacher(lessonAndTeacher2);
        if (num==0){
            return 0;
        }
        //查询可约课信息
        List<StuAutoBookClassTime> listInfo=stuAutoBookClassTimeMapper.selectAutoBookClassInfoByPersonId(personId);
        if (listInfo!=null && listInfo.size()>0) {
            Map<String,Object> map=personMapper.selectTokenInfoByPersonId(personId);
            String tokenString=EncryptAndDecrypt.encrypt(JSON.toJSONString(map));

            //获取上周日日期
            LocalDate localDate = LocalDate.now().with(TemporalAdjusters.previous(java.time.DayOfWeek.SUNDAY));
            long currentTime = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            DayOfWeek dayOfWeek=LocalDate.now().getDayOfWeek();
            for (StuAutoBookClassTime result : listInfo) {
                //约本周课程
                LocalDate classDate = localDate.plusDays(result.getWeekId());
                LocalDateTime classDateTime = LocalDateTime.of(classDate, result.getClassTime());
                if (classDateTime.plusHours(-1).toInstant(ZoneOffset.of("+8")).toEpochMilli() >= currentTime) {
                    long classTime = classDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    long classDateTimestamp = classDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
                    if (result.getSurplusValid().getTime() >= classDateTimestamp && result.getStartDate().getTime() <= classDateTimestamp) {
                        invokingService.autoBookCourseByStudent(result.getOrderId(), classTime, "admin", 1, 4, 100, result.getSwitchAllow() == 1 ? 0 : 1, 1, new TeacherProperty(),tokenString);
                    }
                }
                //约下周课程
                classDate = localDate.plusDays(result.getWeekId() + 7);
                long classTime = LocalDateTime.of(classDate, result.getClassTime()).toInstant(ZoneOffset.of("+8")).toEpochMilli();
                long classDateTimestamp = classDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
                if (result.getSurplusValid().getTime() >= classDateTimestamp && result.getStartDate().getTime() <= classDateTimestamp) {
                    invokingService.autoBookCourseByStudent(result.getOrderId(), classTime, "admin", 1, 4, 100, result.getSwitchAllow() == 1 ? 0 : 1, 1, new TeacherProperty(),tokenString);
                }
                //如果是周5、6、日则多约一周课程
                if (dayOfWeek.getValue()>4){
                    //约下下周课程
                    classDate = localDate.plusDays(result.getWeekId() + 14);
                    classTime = LocalDateTime.of(classDate, result.getClassTime()).toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    classDateTimestamp = classDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
                    if (result.getSurplusValid().getTime() >= classDateTimestamp && result.getStartDate().getTime() <= classDateTimestamp) {
                        invokingService.autoBookCourseByStudent(result.getOrderId(), classTime, "admin", 1, 4, 100, result.getSwitchAllow() == 1 ? 0 : 1, 1, new TeacherProperty(),tokenString);
                    }
                }
            }
        }
        return num;
    }

    /**
     * 调整常用老师顺序
     * @param originalIndex 互换常用老师位置
     * @param newIndex 互换常用老师位置
     * @param personId 用户id
     * @return
     */
    @Override
    public int changeCommonlyUsedTeacher(int originalIndex, int newIndex, int personId){
        StudentInfo record=personMapper.selectCommonTeacherByPersonId(personId);
        Integer teacher1Id=record.getTeacherId1();
        Integer teacher2Id=record.getTeacherId2();
        Integer teacher3Id=record.getTeacherId3();
        switch (originalIndex){
            case 1:
                if (newIndex==2){
                    teacher1Id=record.getTeacherId2();
                    teacher2Id=record.getTeacherId1();
                } else if (newIndex==3){
                    teacher1Id=record.getTeacherId3();
                    teacher3Id=record.getTeacherId1();
                }
                break;

            case 2:
                if (newIndex==1){
                    teacher1Id=record.getTeacherId2();
                    teacher2Id=record.getTeacherId1();
                } else if (newIndex==3){
                    teacher2Id=record.getTeacherId3();
                    teacher3Id=record.getTeacherId2();
                }
                break;
            case 3:
                if (newIndex==1){
                    teacher1Id=record.getTeacherId3();
                    teacher3Id=record.getTeacherId1();
                } else if (newIndex==2){
                    teacher2Id=record.getTeacherId3();
                    teacher3Id=record.getTeacherId2();
                }
                break;
            default:

        }
        return personMapper.updateCommonTeacherByPersonId(teacher1Id,teacher2Id,teacher3Id,personId);
    }

    @Override
    public List<GradeLevel> ageGroupList() {
        return personMapper.ageGroupList();
    }

    @Override
    public List<GradeLevel> teachingStyleList() {
        return personMapper.teachingStyleList();
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int saveStuPrefer(StuPreferences stuPreferences) {

        if (stuPreferences.getSwitchAuto()==null){
            stuPreferences.setSwitchAuto(0);
        }
        if (stuPreferences.getSwitchAllow()==null){
            stuPreferences.setSwitchAllow(0);
        }
        //studentInfoMapper.updateSwitchByPersonId(stuPreferences.getPersonId(),stuPreferences.getSwitchAuto(),stuPreferences.getSwitchAllow());

        StuPreferences preferIsExist = personMapper.stuPrefer(stuPreferences.getPersonId());
        StuPreferences stuPreferConfig;
        List<StuPreferences> stuPreferConfigList = new ArrayList<>();
        if(stuPreferences.getCharacter() == null){
            stuPreferences.setCharacter(0);
        }

        if(stuPreferences.getTeacherSex() == null){
            stuPreferences.setTeacherSex(0);
        }
        if(stuPreferences.getEnBasis() == null){
            stuPreferences.setEnBasis(0);
        }
        /*if(stuPreferences.getMonday() == null){
            stuPreferences.setMonday(0);
        }else{
             stuPreferConfig = new StuPreferences();
             stuPreferConfig.setWeekId(1);
             stuPreferConfig.setPersonId(stuPreferences.getPersonId());
             stuPreferConfig.setOftenUseClassTimeId(stuPreferences.getMonday());
             stuPreferConfig.setAddUserName(stuPreferences.getAddUserName());
             stuPreferConfigList.add(stuPreferConfig);
        }
        if(stuPreferences.getTuesday() == null){
            stuPreferences.setTuesday(0);
        }else{
             stuPreferConfig = new StuPreferences();
             stuPreferConfig.setWeekId(2);
             stuPreferConfig.setPersonId(stuPreferences.getPersonId());
             stuPreferConfig.setOftenUseClassTimeId(stuPreferences.getTuesday());
             stuPreferConfig.setAddUserName(stuPreferences.getAddUserName());
             stuPreferConfigList.add(stuPreferConfig);
        }
        if(stuPreferences.getWednesday() == null){
            stuPreferences.setWednesday(0);
        }else {
             stuPreferConfig = new StuPreferences();
             stuPreferConfig.setWeekId(3);
             stuPreferConfig.setPersonId(stuPreferences.getPersonId());
             stuPreferConfig.setOftenUseClassTimeId(stuPreferences.getWednesday());
             stuPreferConfig.setAddUserName(stuPreferences.getAddUserName());
             stuPreferConfigList.add(stuPreferConfig);
        }
        if(stuPreferences.getThursday() == null){
            stuPreferences.setThursday(0);
        }else{
             stuPreferConfig = new StuPreferences();
             stuPreferConfig.setWeekId(4);
             stuPreferConfig.setPersonId(stuPreferences.getPersonId());
             stuPreferConfig.setOftenUseClassTimeId(stuPreferences.getThursday());
             stuPreferConfig.setAddUserName(stuPreferences.getAddUserName());
             stuPreferConfigList.add(stuPreferConfig);
        }
        if(stuPreferences.getFriday() == null){
            stuPreferences.setFriday(0);
        }else{
             stuPreferConfig = new StuPreferences();
             stuPreferConfig.setWeekId(5);
             stuPreferConfig.setPersonId(stuPreferences.getPersonId());
             stuPreferConfig.setPersonId(stuPreferences.getPersonId());
             stuPreferConfig.setOftenUseClassTimeId(stuPreferences.getFriday());
             stuPreferConfig.setAddUserName(stuPreferences.getAddUserName());
             stuPreferConfigList.add(stuPreferConfig);
        }
        if(stuPreferences.getSaturday() == null){
            stuPreferences.setSaturday(0);
        }else{
            stuPreferConfig = new StuPreferences();
            stuPreferConfig.setWeekId(6);
            stuPreferConfig.setPersonId(stuPreferences.getPersonId());
            stuPreferConfig.setOftenUseClassTimeId(stuPreferences.getSaturday());
            stuPreferConfig.setAddUserName(stuPreferences.getAddUserName());
            stuPreferConfigList.add(stuPreferConfig);
        }
        if(stuPreferences.getSunday() == null){
            stuPreferences.setSunday(0);
        }else{
            stuPreferConfig = new StuPreferences();
            stuPreferConfig.setWeekId(7);
            stuPreferConfig.setPersonId(stuPreferences.getPersonId());
            stuPreferConfig.setOftenUseClassTimeId(stuPreferences.getSunday());
            stuPreferConfig.setAddUserName(stuPreferences.getAddUserName());
            stuPreferConfigList.add(stuPreferConfig);
        }*/

        if(stuPreferConfigList.size() > 0){
            personMapper.delStuPreferConfig(stuPreferences.getPersonId());
            personMapper.addStuPreferConfig(stuPreferConfigList);
        }else{
            personMapper.delStuPreferConfig(stuPreferences.getPersonId());
        }

        if(preferIsExist != null){
            return  personMapper.updataStuPrefer(stuPreferences);
        }else{
            return personMapper.addStuPrefer(stuPreferences);
        }

    }

    @Override
    public StuPreferences stuPrefer(int personId) {
        List<StuPreferences> stuPreferListByPersonId = this.stuPreferListByPersonId(personId);
        StuPreferences stuPrefer2 = personMapper.stuPrefer(personId);
        /*for(StuPreferences sf : stuPreferListByPersonId){
            if(sf.getWeekId() == 1){
                stuPrefer2.setMonday(sf.getOftenUseClassTimeId());
            }
            if(sf.getWeekId() == 2){
                stuPrefer2.setTuesday(sf.getOftenUseClassTimeId());
            }
            if(sf.getWeekId() == 3){
                stuPrefer2.setWednesday(sf.getOftenUseClassTimeId());
            }
            if(sf.getWeekId() == 4){
                stuPrefer2.setThursday(sf.getOftenUseClassTimeId());
            }
            if(sf.getWeekId() == 5){
                stuPrefer2.setFriday(sf.getOftenUseClassTimeId());
            }
            if(sf.getWeekId() == 6){
                stuPrefer2.setSaturday(sf.getOftenUseClassTimeId());
            }
            if(sf.getWeekId() == 7){
                stuPrefer2.setSunday(sf.getOftenUseClassTimeId());
            }
        }*/
        return stuPrefer2;
    }

    @Override
    public String searchSuggestion(int personId){
        return personMapper.selectSuggestion(personId);
    }

    @Override
    public StudentInfo stuAge(int personId) {
        return personMapper.stuAge(personId);
    }

    @Override
    public List<StuPreferences> stuPreferListByPersonId(int personId) {
        return personMapper.stuPreferListByPersonId(personId);
    }

    /**
     * 查询学员客户属性
     * @param personId 学员id
     * @return 学员客户属性
     */
    @Override
    public Map<String,Object> searchRevisitByPersonId(Integer personId){
        return personMapper.selectRevisitByPersonId(personId);
    }

    @Override
    public StudentInfo pcpInfo(int personId) {
        return personMapper.pcpInfo(personId);
    }

    /**
     * 查询生成pcp记录
     * @param personId 学员id
     * @return
     */
    @Override
    public List<String> selectPcpRecordByPersonId(int personId){
        return personMapper.selectPcpRecordByPersonId(personId);
    }

    /**
     * 查询店铺信息，学员列表里使用
     * @param listIds 已选id
     * @return
     */
	@Override
	public List<Map<String,Object>> searchSelectListByStuList(List<Integer> listIds) {
        List<Map<String,Object>> listMap=new ArrayList<>();
        List<Map<String,Object>> list = storesMapper.selectByStuList();
        if (list!=null && list.size()>0){
            List<Map<String,Object>> dataList=null;
            Map<String,Object> dataMap;
            Map<String,Object> map;
            int storesType=0;
            for (Map<String, Object> aList : list) {
                //判断是否同一店铺类型
                if (storesType != Integer.parseInt(aList.get("type").toString())) {
                    storesType = Integer.parseInt(aList.get("type").toString());
                    //店铺类型信息
                    map = new HashMap<>(4);
                    map.put("id", storesType);
                    map.put("name", aList.get("typeName"));
                    map.put("checked", false);
                    //店铺类型的所有店铺
                    dataList = new ArrayList<>();
                    map.put("list", dataList);
                    listMap.add(map);
                }
                //店铺信息
                dataMap = new HashMap<>(2);
                dataMap.put("id", Integer.parseInt(aList.get("id").toString()));
                dataMap.put("name", aList.get("name"));
                dataMap.put("checked", false);
                //判断店铺是否已选择
                if (listIds != null) {
                    for (Integer id : listIds) {
                        if (id == Integer.parseInt(aList.get("id").toString())) {
                            dataMap.put("checked", true);
                            listIds.remove(id);
                            break;
                        }
                    }
                }
                dataList.add(dataMap);
            }
        }

        //判断店铺类型是否选择，根据旗下的店铺是否已全选
        for (Map<String, Object> map : listMap) {
            //已选择店铺数
            int checkedNum=0;
            List<Map<String, Object>> listTemp=(List<Map<String, Object>>)map.get("list");
            for (Map<String, Object> dataMap : listTemp) {
                if ((boolean)dataMap.get("checked")){
                    checkedNum+=1;
                }else {
                    break;
                }
            }
            if (checkedNum>0 && checkedNum==listTemp.size()){
                map.put("checked",true);
            }
        }

        return listMap;
	}

    @Override
	public List<Map<String,Object>> searchChannelInfo(List<Integer> listIds) {
		List<Map<String,Object>> listMap=new ArrayList<>();
		try{
			List<Map<String,Object>> list = personMapper.selectChannelInfoByType();
			if (list!=null && list.size()>0){
				List<Map<String,Object>> dataList=null;
				Map<String,Object> dataMap=null;
				Map<String,Object> map;
				int channelType=0;
				for (Map<String,Object> aMap:list){
					if (channelType!=Integer.parseInt(aMap.get("type").toString())){
                        channelType=Integer.parseInt(aMap.get("type").toString());
						map=new HashMap<>(4);
						map.put("id",aMap.get("type"));
						map.put("name",aMap.get("name"));
						map.put("checked",false);
						dataList=new ArrayList<>();
						map.put("list",dataList);
						listMap.add(map);
					}
					dataMap=new HashMap<>(3);
					dataMap.put("id",aMap.get("id"));
					dataMap.put("name",aMap.get("channelName"));
					dataMap.put("checked",false);
					if (listIds!=null && listIds.size()>0){
						for (Integer id:listIds){
							if (id==Integer.parseInt(aMap.get("id").toString())){
                                dataMap.put("checked",true);
                                listIds.remove(id);
                                break;
							}
						}
					}
					dataList.add(dataMap);
				}

                //判断渠道类型是否选择，根据旗下的渠道是否已全选
                for (Map<String, Object> map1 : listMap) {
                    //已选择渠道数
                    int checkedNum=0;
                    List<Map<String, Object>> listTemp=(List<Map<String, Object>>)map1.get("list");
                    for (Map<String, Object> aMap : listTemp) {
                        if ((boolean)aMap.get("checked")){
                            checkedNum+=1;
                        }else {
                            break;
                        }
                    }
                    if (checkedNum==listTemp.size()){
                        map1.put("checked",true);
                    }
                }
			}
		}catch(Exception e){
            logger.error(e.getMessage(),e);
		}
		return listMap;
	}

	@Override
    public List<Map<String, Object>> stateListMap(List<Integer> listIds,List<Integer>parentIds) {
	    List<Map<String,Object>> listMap=new ArrayList<>();
	    //客户属性所有第一级父类
        List<Map<String,Object>> list = personMapper.selectRevisitList(1);
        if (list!=null && list.size()>0){
            List<Map<String,Object>> dataList;
            Map<String,Object> dataMap;
            Map<String,Object> map;
            for (Map<String, Object> aList : list) {
                map = new HashMap<>();
                map.put("id", Integer.parseInt(aList.get("id").toString()));
                if ("潜在客户".equals(aList.get("name").toString())){
                    map.put("name", "客户");
                }else if ("正式学员".equals(aList.get("name").toString())){
                    map.put("name", "在读学员");
                }else if ("已上可跟进".equals(aList.get("name").toString())){
                    map.put("name", "已完成DEMO");
                }else{
                    map.put("name", aList.get("name"));
                }

                map.put("checked", false);
                //客服属性下所有子类
                dataList = new ArrayList<>();
                List<Map<String,Object>> dataList2 = personMapper.selectChildRevisitInfo(Integer.parseInt(aList.get("id").toString()));
                listMap.add(map);
                if (dataList2.size()==1){
                    dataList2.clear();
                }
                //判断客服属性是否已选择
                if (listIds != null) {

                    for(Map<String, Object> mapList: dataList2){
                         //店铺信息
                        dataMap = new HashMap<>();
                        dataMap.put("id", Integer.parseInt(mapList.get("id").toString()));
                        dataMap.put("name", mapList.get("name"));
                        dataMap.put("parentId", mapList.get("parent_id"));
                        dataMap.put("checked", false);
                        for (Integer id : listIds) {
                             if (id == Integer.parseInt(mapList.get("id").toString())) {
                                dataMap.put("checked", true);
                                listIds.remove(id);
                                break;
                            }
                         }
                        dataList.add(dataMap);
                        map.put("list", dataList);
                    }
                }else{
                   for(Map<String, Object> mapList: dataList2){
                        //店铺信息
                       dataMap = new HashMap<>();
                       dataMap.put("id", Integer.parseInt(mapList.get("id").toString()));
                       dataMap.put("name", mapList.get("name"));
                       dataMap.put("parentId", mapList.get("parent_id"));
                       dataMap.put("checked", false);
                       dataList.add(dataMap);
                   }
                    map.put("list", dataList);
                }
            }
        }

        //判断店铺类型是否选择，根据旗下的店铺是否已全选
        for (Map<String, Object> map : listMap) {
            //已选择店铺数
            if(parentIds != null && parentIds.size()>0){
                for (int parentId: parentIds) {
                    if (parentId == Integer.parseInt(map.get("id").toString())){
                       map.put("checked",true);
                    }
                }
            }
        }
        return listMap;
    }

    @Override
    public List<Stores> searchStores() {
        return storesMapper.searchStores();
    }

    /**
	 * @Title: combineSydwCore
	 * @Description: 该方法是用于相同对象不同属性值的合并，如果两个相同对象中同一属性都有值，
	 *               那么sourceBean中的值会覆盖tagetBean重点的值
	 * @author: James
	 * @date: 2019年03月12日 下午1:53:19
	 * @param sourceBean
	 *            被提取的对象bean
	 * @param targetBean
	 *            用于合并的对象bean
	 * @return targetBean 合并后的对象
	 * @return: Object
	 */
	private StudentInfo combineSydwCore(Object sourceBean, Object targetBean) {
		Class sourceBeanClass = sourceBean.getClass();
		Class targetBeanClass = targetBean.getClass();

		Field[] sourceFields = sourceBeanClass.getDeclaredFields();
		Field[] targetFields = sourceBeanClass.getDeclaredFields();
		for (int i = 0; i < sourceFields.length; i++) {
			Field sourceField = sourceFields[i];
			Field targetField = targetFields[i];
			sourceField.setAccessible(true);
			targetField.setAccessible(true);
			try {
				if ((sourceField.get(sourceBean) != null)) {
					targetField.set(targetBean, sourceField.get(sourceBean));
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return (StudentInfo)targetBean;
	}

    @Override
    public Map<String,Object> getStudentList(PersonParamter personParameter) {
	    Map<String,Object> resultMap = new HashMap<>(2);
        if (personParameter.getPage() == null || personParameter.getPage() <1) {
            personParameter.setPage(1);
        }
        if (personParameter.getLimit() == null) {
            personParameter.setLimit(10);
        }
        /*if (Integer.parseInt(session.getAttribute("roleflag").toString()) <= 1) {
            if (Integer.parseInt(session.getAttribute("roleId").toString()) == 2 || (Integer.parseInt(session.getAttribute("roleId").toString()) == 12)){
                personParameter.setShareAreaId(Integer.parseInt(session.getAttribute("shareAreaId").toString()));
            } else {
                if (Integer.parseInt(session.getAttribute("storesId").toString()) != 1) {
                    personParameter.setShareAreaId(Integer.parseInt(session.getAttribute("shareAreaId").toString()));
                }
            }
        }*/
        //市场人员只能查看自己学员号录入的学员
        if (Integer.parseInt(session.getAttribute("roleId").toString())==6){
            if(session.getAttribute("personId")!=null && Integer.parseInt(session.getAttribute("personId").toString())>0){
                String loginName=personMapper.selectLoginNameByPersonId(Integer.parseInt(session.getAttribute("personId").toString()));
                personParameter.setQrcode(loginName);
            }else {
                personParameter.setQrcode(session.getAttribute("loginname").toString());
            }
            personParameter.setRegister(session.getAttribute("loginname").toString());
        }
        //获取查询学员列表的条件
        this.getPersonParameters(personParameter);
        //查询总记录数
        int total = personMapper.personCounter(personParameter);
        resultMap.put("total",total);
        int totalPage= (int) Math.ceil(total/(double) personParameter.getLimit());
        if (totalPage>0 && totalPage<personParameter.getPage()){
            personParameter.setPage(totalPage);
        }
        //分页 从多少条开始
        int fromRows = (personParameter.getPage()-1)*personParameter.getLimit();
        personParameter.setFromRows(fromRows);
        List<StudentInfo> personList = personMapper.searchStudentInfoByPage(personParameter);
        List<Integer> listPersonId = new ArrayList<>(personParameter.getLimit());
        if(personList != null && personList.size() > 0){
            for (StudentInfo studentInfo : personList) {
                listPersonId.add(studentInfo.getPersonId());
            }
            if(listPersonId.size() > 0){
                //新的学员信息列表对象
                List<StudentInfo> list = new ArrayList<>();
                //查询学员非where条件显示信息
                List<StudentInfo> personInfoList = personMapper.personInfoForPage(listPersonId);
                if(personInfoList != null && personInfoList.size() > 0){
                    for (StudentInfo studentInfo : personList) {
                        for (StudentInfo info : personInfoList) {
                            if (studentInfo.getPersonId().equals(info.getPersonId())) {
                                list.add(combineSydwCore(studentInfo, info));
                                personInfoList.remove(info);
                                break;
                            }
                        }
                    }
                    personList.clear();
                }
                //查询用户已抢单数量和是否可以继续抢单
                Ccgetstudent ccgetstudent=null;
                if (Integer.parseInt(session.getAttribute("storeType").toString()) <= 4
                        && (Integer.parseInt(session.getAttribute("roleId").toString()) == 2 || Integer.parseInt(session.getAttribute("roleId").toString()) == 12)) {
                    ccgetstudent=this.selectCCGetStudent(Integer.parseInt(session.getAttribute("userid").toString()),Integer.parseInt(session.getAttribute("robCase").toString()));
                }
                for (StudentInfo studentInfo : list) {
                    if (ccgetstudent != null) {
                        studentInfo.setStuNum(ccgetstudent.getGetnum());
                        studentInfo.setFlag(ccgetstudent.isFlag());
                    }
                }
                //查询学员奖学金状态
                List<StudentInfo> listScholarship = personMapper.selectScholarshipState(listPersonId);
                if (listScholarship!=null && listScholarship.size()>0){
                    for (StudentInfo studentInfo : list) {
                        for (StudentInfo scholarship : listScholarship) {
                            if (studentInfo.getPersonId().equals(scholarship.getPersonId())) {
                                studentInfo.setScholarship(scholarship.getScholarship());
                                listScholarship.remove(scholarship);
                                break;
                            }
                        }
                    }
                }
                resultMap.put("personList",list);
            }
        }
        return resultMap;
    }

    /**
     * 查询是否可以抢单和已抢单数量
     * @param userId 课程顾问id
     * @param robCase 允许抢单数量
     * @return Ccgetstudent
     */
    private Ccgetstudent selectCCGetStudent(Integer userId,Integer robCase) {
        Ccgetstudent ccgetstudent=ccgetstudentMapper.selectCCGetStudent(userId, DateUtil.getToday());
        if (ccgetstudent==null){
            ccgetstudent=new Ccgetstudent();
            ccgetstudent.setGetnum(0);
        }
        if (robCase==null || robCase<0){
            robCase=5;
        }
        LocalTime localTime=LocalTime.now();
        LocalTime startTime = LocalTime.parse("09:00:00");
        LocalTime endTime = LocalTime.parse("23:00:00");
        if (localTime.isAfter(startTime) && localTime.isBefore(endTime) && ccgetstudent.getGetnum()<robCase){
            ccgetstudent.setFlag(true);
        }else {
            ccgetstudent.setFlag(false);
        }
        return ccgetstudent;
    }

    /**
     * 拼接查询学员列表的条件参数
     * @param personParameter 前端传入参数
     */
    private void getPersonParameters(PersonParamter personParameter) {
        if (personParameter==null){
            personParameter=new PersonParamter();
        }
        if (personParameter.getCcIds() != null && personParameter.getCcIds().size() > 0) {
            if (personParameter.getCcIds().get(0) == 0) {
                personParameter.setCcId(0);
                personParameter.setUserId(Integer.parseInt(session.getAttribute("userid").toString()));
                personParameter.getCcIds().clear();
            }

            if (personParameter.getCcId() != null && 0 == personParameter.getCcId()) {
                personParameter.getCcIds().add(0);
                personParameter.setCcIdsList(new ArrayList<>(0));
            }else {
                personParameter.setCcIdsList(personParameter.getCcIds());
            }
        }
        int storeType=Integer.parseInt(session.getAttribute("storeType").toString());
        int roleId=Integer.parseInt(session.getAttribute("roleId").toString());
        int shareAreaId=Integer.parseInt(session.getAttribute("shareAreaId").toString());
        int storesId=Integer.parseInt(session.getAttribute("storesId").toString());
        int userid=Integer.parseInt(session.getAttribute("userid").toString());
        if (storeType <= 4) {
            //cc 相关操作
            if (roleId == 2 || roleId == 12
                    && (personParameter.getCcIds() == null || personParameter.getCcIds().size() == 0)) {
                if (personParameter.getCcId() == null) {
                    personParameter.setCcId(userid);
                }
                personParameter.setStoresType(storeType);
                personParameter.setShareAreaId(shareAreaId);
                personParameter.setStoresId(storesId);
                personParameter.setState(1);//cc cc经理
            } else {
                if (storesId == 1) {
                    //旗舰店非cc cc经理
                    personParameter.setState(3);
                } else {
                    if (session.getAttribute("storeType") != null && storeType >=4) {
                        //加盟店
                        personParameter.setState(4);
                    }else {
                        //线下店非cc cc经理
                        personParameter.setState(2);
                    }
                    if (personParameter.getCcId() == null) {
                        personParameter.setCcId(userid);
                    }
                    personParameter.setShareAreaId(shareAreaId);
                    personParameter.setStoresId(storesId);
                }
            }
            //ssc 相关操作
            if (roleId == 8 || roleId == 15) {
                if (StringUtil.isEmpty(personParameter.getSearch())) {
                    personParameter.setSscId(userid);
                } else {
                    personParameter.setSscId(null);
                }
            }
            //bcc相关操作
            if (roleId == 19) {
                personParameter.setBccId(userid);
            }

            /*if (personParameter.getStoresId() == null) {
                if (session.getAttribute("storeType") != null && Integer.parseInt(session.getAttribute("storeType").toString()) >4) {
                    //加盟店
                    personParameter.setState(4);
                    personParameter.setShareAreaId(Integer.parseInt(session.getAttribute("shareAreaId").toString()));
                    personParameter.setStoresId(Integer.parseInt(session.getAttribute("storesId").toString()));
                }
            }*/

            if (personParameter.getUserId() != null && personParameter.getUserId() == 0) {
                personParameter.getCcIds().clear();
                personParameter.getCcIds().add(personParameter.getUserId());
            }

            if (personParameter.getTestmark() == null){
                personParameter.setTestmark(1);
            }
        }
    }

    @Override
    public Stores selectStoreInfoById(int storesId){
	    return storesMapper.selectStoreInfoById(storesId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int setCc(int personId, int ccId, int storesId, int flag, int maxRobCase,String phone,int isSms,String contactTime,String studentLogin) {
	    Ccgetstudent ccstudent = null;
	    if(flag != 0){
            ccstudent = ccgetstudentMapper.selectByPrimaryKey(ccId);
            if(ccstudent!=null && DateUtil.format(ccstudent.getUpdateTime()).equals(DateUtil.getToday())){
                if(flag==1 && (ccstudent.getGetnum() != null && maxRobCase<1 || ccstudent.getGetnum() >= maxRobCase)){
                    //同一天以内抢单8以上，不允许再抢
                    return -1;
                }
            }
        }
        int result = personMapper.updateCcByPersonId(personId, ccId, storesId);
        if(result > 0){
            if(flag != 0){
                if(ccstudent!=null && ccstudent.getUserId()>0){
                    if(DateUtil.format(ccstudent.getUpdateTime()).equals(DateUtil.getToday())){
                        ccstudent.setGetnum(ccstudent.getGetnum()+1);
                    }else{
                        ccstudent.setGetnum(1);
                    }
                    ccstudent.setUpdateTime(DateUtil.getCurrentDatetime());
                    result = ccgetstudentMapper.updateByPrimaryKeySelective(ccstudent);
                }else{
                    ccstudent=new Ccgetstudent();
                    ccstudent.setUserId(ccId);
                    ccstudent.setGetnum(1);
                    ccstudent.setUpdateTime(DateUtil.getCurrentDatetime());
                    result = ccgetstudentMapper.insertSelective(ccstudent);
                }
            }else{
                List<Integer> ids = new ArrayList<>();
                ids.add(personId);
                Map<String,Object> map = new HashMap<>();
                Person oldccssc = personMapper.selectByPersonId(personId);
                map.put("userId",ccId);
                map.put("list",ids);
                map.put("newCC",ccId);
                List<Integer> ccList = new ArrayList<>();
                if(oldccssc.getUserId()>0){
                    ccList.add(oldccssc.getUserId());
                    map.put("ccList",ccList);
                }
                personMapper.updateAddUserForTrackRemind(map);
            }
            //添加动态
            if (isSms==1) {
                StudentDynamics studentDynamics = new StudentDynamics();
                studentDynamics.setAddUser(session.getAttribute("loginname").toString());
                studentDynamics.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
                studentDynamics.setAddTime(new Date());
                studentDynamics.setPersonId(personId);
                studentDynamics.setStudentLogin(studentLogin);
                studentDynamics.setContent(String.format("【抢单】已短信告知用户%s前联系",contactTime));
                studentDynamics.setQuestionnaireId(0);
                stuDynamicService.addStudentDynamics(studentDynamics, 0, DateUtil.parse(contactTime,"yyyy-MM-dd HH:mm:ss"), studentDynamics.getAddUserId(), studentDynamics.getAddUserId());
                invokingService.sendGrabTheOrderSms(phone,studentDynamics.getAddUser(),contactTime);
            }
        }
        return result;
    }

    /**
     * 变更cc
     * @param personId 学员id
     * @param ccId 新cc id
     * @param type 区分 转单还是 变更cc
     * @return
     */
    @Override
    public int changeCc(int personId, int ccId, Integer type){
        Person oldCc = this.selectOldCCOrSsc(personId);
        User users = userService.selectByPrimaryKey(ccId);

        int num=personMapper.changeCcByPersonId(personId, ccId, users.getStoresId());
        if (num > 0){
            List<Integer> ids = new ArrayList<>();
            ids.add(personId);
            Map<String,Object> map = new HashMap<>();
            Person oldccssc = personMapper.selectByPersonId(personId);
            map.put("userId",ccId);
            map.put("list",ids);
            map.put("newCC",ccId);
            List<Integer> ccList = new ArrayList<>();
            if(oldccssc.getUserId()>0){
                ccList.add(oldccssc.getUserId());
                map.put("ccList",ccList);
            }
            //提醒面板记录一起转到新cc名下
            personMapper.updateAddUserForTrackRemind(map);

            //添加操作记录
            GrabOrderLogs gl = new GrabOrderLogs();
            gl.setPersonId(personId);
            gl.setAddUserName(session.getAttribute("loginname").toString());
            gl.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
            if(oldCc != null && StringUtil.isNotEmpty(oldCc.getCcName())){
                //原来  有cc
                if(type != null && type == 0){
                    gl.setOperationEvent("操作变更CC，由原CC："+oldCc.getCcName()+"变更为： "+users.getLoginName());
                    gl.setDescription("学生管理->学生基本信息->变更cc");
                    gl.setTypeId(3);
                }else{
                    gl.setOperationEvent("操作变更CC，由原CC："+oldCc.getCcName()+"转给cc： "+users.getLoginName());
                    gl.setDescription("学生管理->学生基本信息->转单");
                    gl.setTypeId(2);
                }
                gl.setOldCcSsc(oldCc.getUserId());
            }else{
                //原来没有cc
                if(type != null && type == 0){
                    gl.setOperationEvent("操作变更CC，配置CC："+users.getLoginName());
                    gl.setDescription("学生管理->学生基本信息->变更cc(配置CC)");
                    gl.setTypeId(3);
                }else{
                    gl.setOperationEvent("操作变更CC，（转单）配置CC："+users.getLoginName());
                    gl.setDescription("学生管理->学生基本信息->转单(配置CC)");
                    gl.setTypeId(2);
                }
            }
            gl.setNewCcSsc(ccId);

            List<GrabOrderLogs> list = new ArrayList<>();
            list.add(gl);
            this.addGrabOrderLogs(list);

        }
        return num;
    }

    @Override
    public int addGrabOrderLogs(List<GrabOrderLogs> list) {
        return grabOrderLogsMapper.addGrabOrderLogs(list);
    }

    @Override
    public int addGrabOrderLogs(GrabOrderLogs record) {
        record.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
        record.setAddUserName(session.getAttribute("loginname").toString());
        List<GrabOrderLogs> list=new ArrayList<>(1);
        list.add(record);
        return grabOrderLogsMapper.addGrabOrderLogs(list);
    }

    @Override
    public Person selectOldCCOrSsc(int personId) {
        return personMapper.selectOldCCOrSsc(personId);
    }

    @Override
    public int delPerson(int state, int personId) {
        return personMapper.delPerson(state,personId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchTransfer(String strIds, Integer ccId, Integer sscId, Integer bccId) {
	    String[] idsArr = strIds.split(",");
        List<Integer> ids = new ArrayList<>();
        List<GrabOrderLogs> logsList = new ArrayList<>();
        User cc = null;
        User ssc= null;
        User bcc= null;
        Map<String, Object> map = new HashMap<>();
        if (ccId != null ) {
            cc = userService.selectByPrimaryKey(ccId);
            map.put("storeId", cc.getStoresId());
        }
        if (sscId != null) {
            ssc = userService.selectByPrimaryKey(sscId);
        }
        if (bccId != null) {
            bcc = userService.selectByPrimaryKey(bccId);
        }
        for (String str : idsArr) {
            ids.add(Integer.parseInt(str));
        }
        List<Person> perList = personMapper.selectBypersonIds(ids);
        List<Integer> ccList = new ArrayList<>();
        List<Integer> sscList = new ArrayList<>();
        List<Integer> bccList = new ArrayList<>();
        for(Person oldCCSSC : perList){
            //插入 变更cc 操作日志
            if (ssc!=null) {
                //插入 变更ssc 操作日志
                GrabOrderLogs glSSC = new GrabOrderLogs();
                glSSC.setPersonId(oldCCSSC.getId());
                glSSC.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
                glSSC.setAddUserName(session.getAttribute("loginname").toString());
                if(oldCCSSC != null && StringUtil.isNotEmpty(oldCCSSC.getSscName())){
                    glSSC.setOperationEvent("批量转移（修改SSC）,由"+oldCCSSC.getSscName()+"变更为"+ssc.getLoginName());
                    glSSC.setOldCcSsc(oldCCSSC.getSscId());
                }else{
                    //原来没有 ssc
                    glSSC.setOperationEvent("成功批量配置SSC:"+ssc.getLoginName());
                }
                glSSC.setTypeId(8);
                glSSC.setNewCcSsc(ssc.getId());
                glSSC.setDescription("学员基本信息->学员信息列表->批量转移");
                logsList.add(glSSC);
                sscList.add(oldCCSSC.getSscId());
            }

             if (cc!=null) {
                 GrabOrderLogs glCC = new GrabOrderLogs();
                 glCC.setPersonId(oldCCSSC.getId());
                 glCC.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
                 glCC.setAddUserName(session.getAttribute("loginname").toString());
                 glCC.setDescription("学员基本信息->学员信息列表->批量转移");
                 if(StringUtil.isNotEmpty(oldCCSSC.getCcName())){
                    glCC.setOperationEvent("批量转移（修改CC）,由"+oldCCSSC.getCcName()+"变更为"+cc.getLoginName());
                    glCC.setOldCcSsc(oldCCSSC.getUserId());
                }else{
                    //原来没有 cc
                    glCC.setOperationEvent("成功批量配置CC："+cc.getLoginName());
                }
                glCC.setTypeId(7);
                glCC.setNewCcSsc(cc.getId());
                logsList.add(glCC);
                ccList.add(oldCCSSC.getCcId());
             }

            if (bcc!=null) {
                GrabOrderLogs glBCC = new GrabOrderLogs();
                glBCC.setPersonId(oldCCSSC.getId());
                glBCC.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
                glBCC.setAddUserName(session.getAttribute("loginname").toString());
                glBCC.setDescription("学员基本信息->学员信息列表->批量转移");
                if(oldCCSSC != null && StringUtil.isNotEmpty(oldCCSSC.getBccName())){
                    glBCC.setOperationEvent("批量转移（修改约课顾问）,由"+oldCCSSC.getBccName()+"变更为"+bcc.getLoginName());
                    glBCC.setOldCcSsc(oldCCSSC.getBccId());
                }else{
                    //原来没有 cc
                    glBCC.setOperationEvent("成功批量配置约课顾问："+bcc.getLoginName());
                }
                glBCC.setTypeId(9);
                glBCC.setNewCcSsc(bcc.getId());
                logsList.add(glBCC);
                bccList.add(oldCCSSC.getBccId());
            }
        }
        map.put("newCC", ccId);
        map.put("newSSC", sscId);
        map.put("newBCC", bccId);
        map.put("list", ids);
        map.put("sscList", sscList);
        map.put("ccList", ccList);
        map.put("bccList", bccList);
        if(ccId != null){
            map.put("userId",ccId);
            personMapper.updateAddUserForTrackRemind(map);
        }
        if(sscId != null){
            map.put("userId",sscId);
            personMapper.updateAddUserForTrackRemind(map);
        }
        int isSuccess = personMapper.updateBatchCCSSC(map);
        if (isSuccess > 0) {
            if (sscId != null) {
                //更改ssc自动添加好友
                Integer sscPersonId=personMapper.selectPersonIdByUserId(sscId);
                if (sscPersonId!=null && sscPersonId>0) {
                    for (Person oldCCSSC : perList) {
                        if (oldCCSSC.getSscId()==0 || oldCCSSC.getSscId()!= sscId) {
                            invokingService.addFriend(oldCCSSC.getId(), sscPersonId);
                        }
                    }
                }
            }
        }
        //批量添加  修改cc ssc
        if(logsList.size() > 0){
             isSuccess = this.addGrabOrderLogs(logsList);
        }
        return isSuccess;
    }

    /**
     * 手机号码合法检测
     * @param mobiles 手机号码
     * @return 结果
     */
    private boolean isMobileNO(String mobiles){
		Pattern p = compile("^((13[0-9])|(17[0-9])|(14[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addStuInfo(StudentInfo studentInfo) {
	    int flag = personMapper.phoneNumIsExist(studentInfo.getPhone(),null,studentInfo.getLoginName());
        if(flag >0){
            //手机号已存在
            return -1;
        }
        if(StringUtil.isEmpty(studentInfo.getQq())){
    		studentInfo.setQq("");
    	}
        studentInfo.setRegister(session.getAttribute("loginname").toString());
        studentInfo.setStoresId(Integer.parseInt(session.getAttribute("storesId").toString()));
    	if (Integer.parseInt(session.getAttribute("storesId").toString()) == 2) {
            studentInfo.setPictures("/etalk/admin/images/bd_logo.png");
        } else if (Integer.parseInt(session.getAttribute("storesId").toString()) == 3) {
            studentInfo.setPictures("/etalk/admin/images/sun_logo.png");
        } else if (Integer.parseInt(session.getAttribute("storesId").toString()) == 10) {
            studentInfo.setPictures("/etalk/admin/images/emate_head.png");
        } else {
            if (StringUtil.isEmpty(studentInfo.getPictures())) {
                studentInfo.setPictures("/img/head/default1.png");
            }
        }

        if (Integer.parseInt(session.getAttribute("roleId").toString()) == 2) {
            studentInfo.setCcId(Integer.parseInt(session.getAttribute("userid").toString()));
            studentInfo.setStoresId(Integer.parseInt(session.getAttribute("storesId").toString()));
        }
        studentInfo.setTeacherId1(0);
        studentInfo.setTeacherId2(0);
        studentInfo.setTeacherId3(0);
        studentInfo.setRoleId(3);
        if(studentInfo.getTestMark() == null){
    		studentInfo.setTestMark(0);
    	}
    	Person per = null;
        if(StringUtil.isNotEmpty(studentInfo.getQrCode()) && studentInfo.getStoresId()==1){
            String phone = "";
            if(studentInfo.getQrCode().trim().length()==11 && isMobileNO(studentInfo.getQrCode().trim())){
				phone = studentInfo.getQrCode();
			}
	    	per = personMapper.selectByPhoneOrLoginName(studentInfo.getQrCode(),phone);
			if(per!=null && per.getId() != null && StringUtil.isNotEmpty(per.getLoginName())){
				studentInfo.setQrCode(per.getLoginName());
			}
    	}

    	int result  = personMapper.addPerson(studentInfo);
        //更改ssc 日志
        List<GrabOrderLogs> logList = new ArrayList<GrabOrderLogs>();
        if(result > 0 ){
            if (studentInfo.getRoleId() == 3) {
                //如果是则添加学生基本信息
                studentInfo.setPersonId(studentInfo.getPersonId());
                if(studentInfo.getState() != null){
                    studentInfo.setState(1);
                }

                personMapper.insertInfo(studentInfo);
                //添加用户性格属性
                this.addPersonDisposition(studentInfo.getPersonId(),studentInfo.getDispositionId());
                //调用运营接口打开小E
                invokingService.openE(studentInfo.getPersonId());
                //添加ssc变更日志
                if (null != studentInfo.getSscId() && studentInfo.getSscId() > 0) {
                    GrabOrderLogs gl = new GrabOrderLogs();
                    User users = userService.selectByPrimaryKey(studentInfo.getSscId());
                    gl.setPersonId(studentInfo.getPersonId());
                    gl.setAddUserId(Integer.parseInt(session.getAttribute("userid").toString()));
                    gl.setAddUserName(session.getAttribute("loginname").toString());
                    gl.setOperationEvent("成功配置SSC：" + users.getLoginName());
                    gl.setDescription("学生管理->学生基本信息(添加)->配置SSC");
                    gl.setOldCcSsc(0);
                    gl.setTypeId(6);
                    gl.setNewCcSsc(studentInfo.getSscId());
                    logList.add(gl);
                    this.addGrabOrderLogs(logList);
                    //添加ssc学习账号为好友
                    Integer sscPersonId=personMapper.selectPersonIdByUserId(studentInfo.getSscId());
                    if (sscPersonId!=null && sscPersonId>0) {
                        invokingService.addFriend(studentInfo.getPersonId(), sscPersonId);
                    }
                }

                if(per != null && per.getTestmark()!=null && (per.getTestmark()==0 || per.getTestmark()==5)){
                    //赠送经验值
                    invokingService.addExperience(per.getId(), 3,studentInfo.getPersonId());
                    invokingService.inviteAndStatus(per.getId(),studentInfo.getPersonId(),1);
                }
                //添加demo课程
                if(StringUtil.isNotEmpty(studentInfo.getQrCode())){
                    if (studentInfo.getChannelId()!=null && studentInfo.getChannelId()==130){
                        //9.9团购渠道送3节体验课
                        kcOrdersService.addKcOrdersByDemo(348, studentInfo.getPersonId(), studentInfo.getStoresId());
                    }else {
                        kcOrdersService.addKcOrdersByDemo(245, studentInfo.getPersonId(), studentInfo.getStoresId());
                    }
                }else{
                    kcOrdersService.addKcOrdersByDemo(244, studentInfo.getPersonId(), studentInfo.getStoresId());
                }
            }
        }

        return result;
    }

    private void addPersonDisposition(Integer personId,String disposition) {
        if (StringUtils.isNotEmpty(disposition)){
            studentJoinDispositionMapper.delete(personId);
            String[] temp=disposition.split(",");
            List<Integer> listDisposition=new ArrayList<>(temp.length);
            for (String id:temp){
                listDisposition.add(Integer.parseInt(id));
            }
            if(listDisposition.size()>0){
                studentJoinDispositionMapper.insert(personId,listDisposition,session.getAttribute("loginname").toString());
            }

        }
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int insertScholarship(StudentScholarship record) {
        return personMapper.insertScholarship(record);
    }

    @Override
    public Map<String, Object> selectStudentScholarship(Integer personId) {
        return personMapper.selectStudentScholarship(personId);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateStateByScholarshipByPersonId(Integer personId) {
        return personMapper.updateStateByScholarshipByPersonId(personId);
    }

    @Override
    public List<StudentInfo> exportPersonList(PersonParamter personParamter) {
        getPersonParameters(personParamter);
        return personMapper.exportPersonList(personParamter);
    }

    /**
     * 查询学员最后一节课程的星星
     *
     * @param personId 学员ID
     * @return 结果
     */
    @Override
    public Integer selectLastLessonStar(int personId) {
        return personMapper.selectLastLessonStar(personId);
    }

    /**
     * 更新pcp学员信息
     *
     * @param personId           学员ID
     * @param learningDifficulty 学习困难
     * @return
     */
    @Override
    public int updatePcpInfo(int personId, String learningDifficulty) {
        return personMapper.updatePcpInfo(personId, learningDifficulty);
    }

    /**
     * 查询老师信息
     * @param teacherId 老师id
     * @return
     */
    @Override
    public TeacherInfoResult searchTeacherInfoByPersonId(int teacherId,int studentId){
        TeacherInfoResult record=personMapper.selectTeacherInfoByPersonId(teacherId);
        List<Integer> list=new ArrayList<>();
        if (StringUtils.isNotEmpty(record.getTeachingStyleIds())){
            for (String id:record.getTeachingStyleIds().split(",")){
                if (StringUtils.isNotEmpty(id)){
                    list.add(Integer.parseInt(id.trim()));
                }
            }
            if (list.size()>0){
                record.setListTeaStyle(personMapper.selectTeachingStyleList(list));
                list.clear();
            }
        }
        if (StringUtils.isNotEmpty(record.getAgeGroupIds())){
            for (String id:record.getAgeGroupIds().split(",")){
                if (StringUtils.isNotEmpty(id)){
                    list.add(Integer.parseInt(id.trim()));
                }
            }
            if (list.size()>0){
                record.setListAgeGroup(personMapper.selectAgeGroupList(list));
                list.clear();
            }
        }
        record.setStudentId(studentId);
        record.setListStar(personMapper.selectStarRateByTeacherLogin(record.getLoginName()));
        record.setListTag(personMapper.selectEvaluationTagsNumberByTeacher(record.getLoginName()));
        if (studentId>0) {
            //查询学员在设置的自动约课时间里，老师空闲时间
            List<StuAutoBookClassTime> bookClassTimeList = stuAutoBookClassTimeMapper.selectAutoBookClassTimeInfoByPersonId(studentId);
            if (bookClassTimeList != null && bookClassTimeList.size() > 0) {
                List<Integer> listWeek = new ArrayList<>(bookClassTimeList.size());
                List<LocalTime> listTime = new ArrayList<>(bookClassTimeList.size());
                for (StuAutoBookClassTime bookClassTime : bookClassTimeList) {
                    if (bookClassTime.getWeekId() == 7) {
                        listWeek.add(0);
                    } else {
                        listWeek.add(bookClassTime.getWeekId());
                    }
                    listTime.add(bookClassTime.getClassTime());
                }
                record.setListFreeSchedule(lessonsMapper.selectFreeScheduleListByPersonId(record.getLoginName(), listWeek, listTime));
            }
        }
        //查询老师下周班表被设置自动约课的学员数
        LocalDate startDate=LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        LocalDate endDate=startDate.plusDays(7);
        List<TeacherClassSchedule> teacherClassScheduleList=lessonsMapper.selectTeacherClassTimeByPersonId(teacherId,startDate,endDate);
        if (teacherClassScheduleList!=null && teacherClassScheduleList.size()>0){
            Map<String,List<TeacherClassSchedule>> teacherClassScheduleMap=new HashMap<> (8);
            List<TeacherClassSchedule> tempList=null;
            int weekId=-1;
            for (TeacherClassSchedule items:teacherClassScheduleList){
                if (weekId!=items.getWeekId()){
                    weekId=items.getWeekId();
                    tempList=new ArrayList<>();
                    teacherClassScheduleMap.put(String.valueOf(weekId),tempList);
                }
                tempList.add(items);
            }
            //查询老师课程班表最大和最小时间
            Map<String,String> maxMinClassTime=lessonsMapper.selectTeacherMaxMinClassTimeByPersonId(teacherId,startDate,endDate);
            for (int i=0;i<7;i++){
                tempList=teacherClassScheduleMap.get(String.valueOf(i));
                if (tempList!=null && tempList.size()>0){
                    int tempWeekId=tempList.get(0).getWeekId();
                    LocalTime minClassTime=tempList.get(0).getClassTime();
                    LocalTime maxClassTime=tempList.get(tempList.size()-1).getClassTime();
                    LocalTime maxTime=LocalTime.parse(maxMinClassTime.get("max_class_time"));
                    LocalTime minTime=LocalTime.parse(maxMinClassTime.get("min_class_time"));
                    //补齐老师缺失时间表按钮
                    while (minTime.isBefore(minClassTime)){
                        minClassTime=minClassTime.plusMinutes(-20);
                        TeacherClassSchedule temp=new TeacherClassSchedule();
                        temp.setClassTime(minClassTime);
                        temp.setWeekId(tempWeekId);
                        temp.setStatus(0);
                        temp.setTotal1(0);
                        temp.setTotal2(0);
                        temp.setTotal3(0);
                        tempList.add(0,temp);
                    }
                    while (maxClassTime.isBefore(maxTime)){
                        maxClassTime=maxClassTime.plusMinutes(20);
                        TeacherClassSchedule temp=new TeacherClassSchedule();
                        temp.setClassTime(maxClassTime);
                        temp.setWeekId(tempWeekId);
                        temp.setStatus(0);
                        temp.setTotal1(0);
                        temp.setTotal2(0);
                        temp.setTotal3(0);
                        tempList.add(temp);
                    }
                }
            }
            record.setClassScheduleMap(teacherClassScheduleMap);
        }

        //查询老师未来两周课表
        record.setScheduleResult(this.searchTeacherScheduleByDoubleWeek(teacherId));


        return record;
    }

    private TeacherScheduleResult searchTeacherScheduleByDoubleWeek(int teacherId){
        TeacherScheduleResult result=new TeacherScheduleResult();
        LocalDate localDate=LocalDate.now();
        Map<String,String> maxMinClassTime=lessonsMapper.selectTeacherMaxMinClassTimeByPersonId(teacherId,localDate,localDate.plusDays(14));
        if (maxMinClassTime==null){
            return result;
        }
        LocalTime maxTime=LocalTime.parse(maxMinClassTime.get("max_class_time"));

        List<TeacherScheduleResult> list=lessonsMapper.selectTeacherScheduleList(teacherId);
        if (list == null){
            list=new ArrayList<>(0);
        }
        for (int i=0;i<14;i++){
            //添加表头日期
            LocalDate localDateTemp=localDate.plusDays(i);
            result.getListDate().add(localDateTemp);
            List<TeacherScheduleResult> listMap=new ArrayList<>();
            //long longtimestamp = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
            LocalTime minTime=LocalTime.parse(maxMinClassTime.get("min_class_time"));
            while (minTime.isBefore(maxTime)){
                TeacherScheduleResult record=new TeacherScheduleResult();
                LocalDateTime classTime=LocalDateTime.of(localDateTemp,minTime);
                record.setClassTime(classTime);
                record.setState(-1);
                for (int j = 0; j < list.size(); j++){
                    LocalDateTime localClassDate=Instant.ofEpochMilli(list.get(j).getReleaseTime().getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
                    if (classTime.isEqual(localClassDate)){
                        record.setState(list.get(j).getState());
                        record.setAutoBooked(list.get(j).getAutoBooked());
                        list.remove(j);
                        break;
                    }else if (j==0 && classTime.isBefore(localClassDate)){
                        break;
                    }
                }
                listMap.add(record);
                minTime=minTime.plusMinutes(20);
            }
            switch (i){
                case 0:
                    result.getList1().addAll(listMap);
                    break;
                case 1:
                    result.getList2().addAll(listMap);
                    break;
                case 2:
                    result.getList3().addAll(listMap);
                    break;
                case 3:
                    result.getList4().addAll(listMap);
                    break;
                case 4:
                    result.getList5().addAll(listMap);
                    break;
                case 5:
                    result.getList6().addAll(listMap);
                    break;
                case 6:
                    result.getList7().addAll(listMap);
                    break;
                case 7:
                    result.getList8().addAll(listMap);
                    break;
                case 8:
                    result.getList9().addAll(listMap);
                    break;
                case 9:
                    result.getList10().addAll(listMap);
                    break;
                case 10:
                    result.getList11().addAll(listMap);
                    break;
                case 11:
                    result.getList12().addAll(listMap);
                    break;
                case 12:
                    result.getList13().addAll(listMap);
                    break;
                case 13:
                    result.getList14().addAll(listMap);
                    break;
                default :
            }


        }
        return result;
    }

    /**
     * 查询老师观看培训资料记录
     * @param listTeaId 老师id
     * @param listFileName 资料文件名
     * @param page 当前页
     * @param pageSize 每页记录数
     * @return
     */
    @Override
    public PageInfo<Map<String,String>> searchTeacherTrainingRecordByPage(Integer[] listTeaId, String[] listFileName, int page, int pageSize){
        if (pageSize<15){
            pageSize=15;
        }
        PageHelper.startPage(page, pageSize);

        return new PageInfo<>(personMapper.selectTeacherTrainingRecordList(listTeaId,listFileName));
    }

    /**
     * 查询老师列表，带级别名称
     * @return
     */
    @Override
    public List<Map<String,Object>> searchTeacherList(){
        List<Map<String,Object>> resultList=new ArrayList<>();
        List<Map<String,Object>> list=personMapper.selectTeacherList();
        if (list!=null && list.size()>0){
            Map<String,Object> tempMap=null;
            List<Map<String,Object>> tempList=null;
            String levelId="0";
            for (Map<String,Object> map:list){
                if (!levelId.equals(map.get("level").toString())){
                    levelId=map.get("level").toString();
                    tempMap=new HashMap<>(14);
                    tempMap.put("levelName",map.get("levelName"));
                    tempList=new ArrayList<>();
                    tempMap.put("list",tempList);
                    resultList.add(tempMap);
                }
                Map<String,Object> tempChildMap=new HashMap<>(2);
                tempChildMap.put("id",map.get("id"));
                tempChildMap.put("loginName",map.get("loginName"));
                tempList.add(tempChildMap);
            }

        }
        return resultList;
    }
}
